package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.NcUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.framework.web.service.DictService;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import com.ruoyi.system.util.ExcelUtil2Element;
import com.ruoyi.system.util.WorkbookExportUtil;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * 标准主 信息操作处理
 *
 * @author ruoyi
 * @date 2019-07-28
 */
@Controller
@RequestMapping("/system/ncStandard")
public class NcStandardController extends BaseController {
    private String prefix = "system/ncStandard";

    @Autowired
    private INcStandardService ncStandardService;

    @Autowired

    private INcStageService stageService;


    @Autowired
    private INcWorkService workService;

    @Autowired
    private INcCaiService caiService;


    @Autowired
    private ISysDictDataService dictDataService;



    @Autowired
    private INcOrderService orderService;

    @Autowired
    private INcMeterialService meterialService;

    /*育苗计划*/
    @GetMapping("/frontStandList")
    public String frontStandList(String beginTime, String endTime, String standardType, String ancestors, ModelMap
            mmap) {
        mmap.put("ancestors", ancestors);
        mmap.put("standardType", standardType);
        mmap.put("beginTime", beginTime);
        mmap.put("endTime", endTime);
        if (!"".equals(standardType)) {
            if ("1".equals(standardType)) {
                return prefix + "/ncStandard1";
            } else if ("2".equals(standardType)) {
                return prefix + "/ncStandard2";
            }
        }
        return "";
    }




    /**
     * 状态修改
     */
    @Log(title = "修改状态", businessType = BusinessType.UPDATE)
    @RequiresPermissions("system:user:edit")
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(NcStandard st) {
        return toAjax(ncStandardService.updateNcStandard(st));
    }


    @RequiresPermissions("system:ncStandard:view")
    @GetMapping()
    public String ncStandard(String standardType, ModelMap mmap) {
        mmap.put("standardType", standardType);
        return prefix + "/ncStandard";
    }

    @RequiresPermissions("system:ncStandard:view")
    @GetMapping("/ncStandardFront")
    public String ncStandardFront(String standardType, ModelMap mmap) {
        mmap.put("standardType", standardType);
        return prefix + "/standardFront";
    }

    @GetMapping("/ncStandardCaiId")
    public String ncStandardCaiId(String type, ModelMap mmap) {

        String[] split = type.split(",");

        String standardType = split[0];
        String caiId = split[1];

        mmap.put("standardType", standardType);
        mmap.put("ancestors", caiId);

        if (!"".equals(caiId)) {

            if ("1".equals(standardType)) {
                return prefix + "/ncStandard1";

            } else if ("2".equals(standardType))

                return prefix + "/ncStandard2";
        }
        return prefix + "/ncStandard";

    }


    /**
     * 查询标准主列表
     */
    @RequiresPermissions("system:ncStandard:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(NcStandard ncStandard) {
        startPage();
        List<NcStandard> list = ncStandardService.selectNcStandardList(ncStandard);
        return getDataTable(list);
    }

    /**
     * 查询标准主列表
     */
    @RequiresPermissions("system:ncStandard:list")
    @PostMapping("/listByCropNameCn/{caiId}")
    @ResponseBody
    public TableDataInfo listByCropNameCn(@PathVariable("caiId") Long caiId, NcStandard ncStandard) {
        startPage();

        //根据菜id查询菜
        ncStandard.setCropVarieties(caiId);

        List<NcStandard> list = ncStandardService.selectNcStandardList(ncStandard);

        return getDataTable(list);
    }

    /**
     * 新增标准主
     */
    @GetMapping("/add")
    public String add(String standardType, ModelMap mmap) {
        mmap.put("standardType", standardType);
        return prefix + "/add";
    }

    /**
     * 新增保存标准主
     */
    @RequiresPermissions("system:ncStandard:add")
    @Log(title = "标准主", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(NcStandard ncStandard) {
        ncStandard.setCreateTime(new Date());
        ncStandard.setStatus("2");
        ncStandard.setCreateBy(ShiroUtils.getLoginName());
        ncStandard = ncStandardService.fillValues(ncStandard,null);
        if (ncStandard == null) {
            return AjaxResult.error("未找到此品种");
        }
        return toAjax(ncStandardService.insertNcStandard(ncStandard));
    }

    /**
     * 修改标准主
     */
    @GetMapping("/edit/{standardId}")
    public String edit(@PathVariable("standardId") Long standardId, ModelMap mmap) {
        NcStandard ncStandard = ncStandardService.selectNcStandardById(standardId);
        mmap.put("ncStandard", ncStandard);
        return prefix + "/edit";
    }

    /**
     * 修改标准周期
     */
    @GetMapping("/config/{standardId}")
    public String config(@PathVariable("standardId") Long standardId, ModelMap mmap) {
        NcStandard ncStandard = ncStandardService.selectNcStandardById(standardId);
        mmap.put("ncStandard", ncStandard);
        return prefix + "/config";
    }

    /**
     * 修改保存标准主
     */
    @RequiresPermissions("system:ncStandard:edit")
    @Log(title = "标准主", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(NcStandard ncStandard) {

        //如果蔬菜品种有变化 则重新 赋值
        NcStandard standardOld = ncStandardService.selectNcStandardById(ncStandard.getStandardId());
        if (standardOld != null && standardOld.getCropVarieties() == ncStandard.getCropVarieties()) {
            return toAjax(ncStandardService.updateNcStandard(ncStandard));
        } else {
            ncStandard = ncStandardService.fillValues(ncStandard,null);
            if (ncStandard == null) {
                return AjaxResult.error("未找到此品种");
            }
            return toAjax(ncStandardService.updateNcStandard(ncStandard));
        }
    }

    /**
     * 删除标准主
     */
    @RequiresPermissions("system:ncStandard:remove")
    @Log(title = "标准主", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(ncStandardService.deleteNcStandardByIds(ids));
    }

    @GetMapping("/showStandard")
    public String showStandard(NcStandard standard, String beginTime, String endTime, ModelMap mmap) {

        if (StringUtils.isNotEmpty(beginTime)) {
            standard.getParams().put("beginTime", beginTime);
        }
        if (StringUtils.isNotEmpty(endTime)) {
            standard.getParams().put("endTime", endTime);
        }

        NcStandard standard1 = new NcStandard();

        //按时间查询育苗计划数量
        //*状态 1:待生成订单 2：待执行 3.在执行 4.已完成*//*
        Map statusCount = ncStandardService.getStatusCount(standard);


        standard.setStandardType("1");
        mmap.put("caiClass1", ncStandardService.getBigCaiClass(standard));


        //育苗标准数量
        int caiClass1Size = 0;
        for (NcCai bigCaiClass : ncStandardService.getBigCaiClass(standard)) {
            int total = (int) bigCaiClass.getPlanCounts().get("total");
            caiClass1Size += total;
        }

        mmap.put("caiClass1Size", caiClass1Size);

        //育苗标准数量
        standard.setStandardType("2");
        standard.setParams(standard.getParams());

        mmap.put("caiClass2", ncStandardService.getBigCaiClass(standard));
        //生产标准数量
        int caiClass2Size = 0;
        for (NcCai bigCaiClass : ncStandardService.getBigCaiClass(standard)) {
            int total = (int) bigCaiClass.getPlanCounts().get("total");
            caiClass2Size += total;
        }

        Map StandTypePre = new HashMap();
        //育苗标准
        StandTypePre.put("type1", caiClass1Size);
        StandTypePre.put("type2", caiClass2Size);


        Integer total = (Integer) statusCount.get("total");
        String type1Precent = NcUtils.getRate(total, StandTypePre, "type1");
        String type2Precent = NcUtils.getRate(total, StandTypePre, "type2");


        statusCount.put("type1Size", caiClass1Size);
        statusCount.put("type2Size", caiClass2Size);
        statusCount.put("type1Precent", type1Precent);
        statusCount.put("type2Precent", type2Precent);
        mmap.put("beginTime", beginTime);
        mmap.put("statusCount", statusCount);
        mmap.put("endTime", endTime);

        return prefix + "/standard1";
    }

    /**
     * 展示标准详情
     */
    @GetMapping("/standDetails/{standardId}")
    public String standDetails(@PathVariable("standardId") Long standardId, ModelMap mmap) {

        NcStandard ncStandard = ncStandardService.selectNcStandardById(standardId);
        mmap.put("ncStandard", ncStandard);

        //查询阶段详情
        NcStage ncStage = new NcStage();
        ncStage.setStandardId(standardId);
        List<NcStage> ncStages = stageService.selectNcStageList(ncStage);
        ncStages.sort(new Comparator<NcStage>() {
            @Override
            public int compare(NcStage nc1, NcStage nc2) {
                return nc1.getOrderNum() - nc2.getOrderNum();//从小到大
            }
        });

        int i = 0;
        for (NcStage stage : ncStages) {
            NcWork ncWork = new NcWork();
            ncWork.setStageId(stage.getStageId());
            List<NcWork> ncWorks = workService.selectNcWorkList(ncWork);
            stage.setWorks(ncWorks);
            if (i == 0) {
                stage.setCssClass("active");
            } else {
                stage.setCssClass("");
            }
            i++;
        }


        mmap.put("ncStages", ncStages);
        return prefix + "/standerDetail1";
    }


    /*阶段 或者 工作 详情*/
    @GetMapping("/detail")
    public String detail(Integer type, Long id, String workDate, ModelMap mmap) {
        //1 :工作详情（镜像） 2：阶段详情（镜像）
        if (type == 2) {
            NcStage stage = stageService.selectNcStageById(id);
            mmap.put("stage", stage);
            return prefix + "/detail-stage";
        } else if (type == 1) {
            NcWork work = workService.selectNcWorkById(id);
            mmap.put("work", work);
            mmap.put("workDate", workDate);
            return prefix + "/detail-work";
        } else {
            return "main";
        }

    }


    /**
     * 新增保存标准主
     */
    @Log(title = "完成计划->标准", businessType = BusinessType.INSERT)
    @PostMapping("/createStandardByPlan")
    @ResponseBody
    public AjaxResult createStandardByPlan(Long plandId) {
        return toAjax(ncStandardService.createStandardByPlan(plandId,ShiroUtils.getSysUser()));
    }

    /**
     * 下载导入模板
     *
     * @return
     */
    @RequiresPermissions("system:ncStandard:view")
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate() {

        WorkbookExportUtil wu = new WorkbookExportUtil(new XSSFWorkbook(), "标准数据导入模板");

        /*标准模板*/
        ExcelUtil2Element<NcStandardTemplate> m_standard = new ExcelUtil2Element<>(NcStandardTemplate.class, wu);
        m_standard.importTemplateExcel("标准数据");

        ExcelUtil2Element<NcStageTemplate> m_stage = new ExcelUtil2Element<>(NcStageTemplate.class, wu);
        m_stage.importTemplateExcel("阶段数据");

        ExcelUtil2Element<NcWorkTemplate> m_mirror = new ExcelUtil2Element<>(NcWorkTemplate.class, wu);
        m_mirror.importTemplateExcel("农事数据");




        /*菜分类基础数据*/
        List<NcCai> cais = caiService.selectCaiListHasParent2(new NcCai());
        //过滤鸡蛋牛奶与菜单类
        cais.removeIf(cai -> cai.getAncestors().contains("210")
                | cai.getAncestors().split(",").length != 3);

        ExcelUtil2Element<NcCai> m_cai = new ExcelUtil2Element<>(NcCai.class, wu);
        m_cai.exportExcel(cais, "菜分类基础数据");

        /*农资数据*/
        List<NcMeterialForStandard> ncMeterialList = meterialService.selectMeterialListHasParent(new NcMeterialForStandard());
        ncMeterialList.removeIf(meterial -> meterial.getAncestors().split(",").length != 3);
        ExcelUtil2Element<NcMeterialForStandard> m_material = new ExcelUtil2Element<>(NcMeterialForStandard.class, wu);
        m_material.exportExcel(ncMeterialList, "农资说明");


        /*单位数据*/
        List<SysDictData> unitType = dictDataService.selectDictDataByType("unitType");
        ExcelUtil2Element<SysDictData> m_unitType_unit = new ExcelUtil2Element<>(SysDictData.class, wu);
        m_unitType_unit.exportExcel(unitType, "农资单位说明");
        return wu.exportExcel();
    }


    @Log(title = "标准管理", businessType = BusinessType.IMPORT)
    @RequiresPermissions("system:ncStandard:import")
    @PostMapping("/importData/{standardType}")

    @ResponseBody
    public AjaxResult importData1(MultipartFile file, @PathVariable("standardType") String standardType, boolean updateSupport) throws Exception {
        SysUser sysUser = ShiroUtils.getSysUser();
        AjaxResult messsage = ncStandardService.importNcStandard(sysUser, standardType, file, updateSupport);
        return messsage;
    }

    /**
     * 导出标准主列表
     */
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(NcStandard ncStandard) {


        WorkbookExportUtil wu = new WorkbookExportUtil(new XSSFWorkbook(), "标准数据");


        List<NcStandard> standardList = ncStandardService.selectNcStandardList(ncStandard);
        ExcelUtil2Element<NcStandard> m_standard = new ExcelUtil2Element<>(NcStandard.class, wu);
        m_standard.exportExcel(standardList,"标准数据");


        List<NcStage> stageList = stageService.selectNcStageList(new NcStage());
        ExcelUtil2Element<NcStage> m_stage = new ExcelUtil2Element<>(NcStage.class, wu);
        m_stage.exportExcel(stageList,"阶段数据");


        List<NcWork> workList = workService.selectNcWorkList(new NcWork());
        ExcelUtil2Element<NcWork> m_work = new ExcelUtil2Element<>(NcWork.class, wu);
        m_work.exportExcel(workList,"农事数据");



        /*菜分类基础数据*/
        List<NcCai> cais = caiService.selectCaiListHasParent2(new NcCai());
        //过滤鸡蛋牛奶与菜单类
        cais.removeIf(cai -> cai.getAncestors().contains("210") | cai.getAncestors().split(",").length != 3);

        ExcelUtil2Element<NcCai> m_cai = new ExcelUtil2Element<>(NcCai.class, wu);
        m_cai.exportExcel(cais, "菜分类基础数据");


        /*农资数据*/
        List<NcMeterialForStandard> ncMeterialList = meterialService.selectMeterialListHasParent(new NcMeterialForStandard());
        ncMeterialList.removeIf(meterial -> meterial.getAncestors().split(",").length != 3);
        ExcelUtil2Element<NcMeterialForStandard> m_material = new ExcelUtil2Element<>(NcMeterialForStandard.class, wu);
        m_material.exportExcel(ncMeterialList, "农资说明");





        /*单位数据*/
        List<SysDictData> unitType = dictDataService.selectDictDataByType("unitType");
        ExcelUtil2Element<SysDictData> m_unitType_unit = new ExcelUtil2Element<>(SysDictData.class, wu);
        m_unitType_unit.exportExcel(unitType, "农资单位说明");



        return wu.exportExcel();

    }


}
